package yz.cp.back.common.utils;

import com.google.common.collect.Maps;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Arrays;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PasswordUtil {
    private static BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    public static String STRONG_PASSWORD = "^(?![a-zA-z]+$)(?!\\d+$)(?![!@#$%^&*]+$)(?![a-zA-z\\d]+$)(?![a-zA-z!@#$%^&*]+$)(?![\\d!@#$%^&*]+$)[a-zA-Z\\d!@#$%^&*]{8,16}$";
    public static String MIDDLE_PASSWORD = "^(?![a-zA-z]+$)(?!\\d+$)(?![!@#$%^&*]+$)[a-zA-Z\\d!@#$%^&*]{8,16}";
    public static String SICK_PASSWORD = "^(?:\\d{8,16}|[a-zA-Z]{8,16}|[!@#$%^&*]{8,16})$";

    public PasswordUtil() {
    }

    public static Boolean matches(String rawPassword, String... encodePassword) {
        Map<String, Boolean> map = Maps.newHashMap();
        map.put("flag", false);
        Arrays.asList(encodePassword).forEach((v) -> {
            if (encoder.matches(rawPassword, v)) {
                map.put("flag", true);
            }

        });
        return (Boolean)map.get("flag");
    }

    public static String encode(String rawPassword) {
        return encoder.encode(rawPassword.trim());
    }

    public static boolean checkPwdFormat(String psw, String pattern) {
        if (psw != null && !psw.isEmpty()) {
            String regex = pattern == null ? STRONG_PASSWORD : pattern;
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(psw);
            return m.matches();
        } else {
            return false;
        }
    }

    public static Integer checkPwd(String psw) {
        if (psw.length() <= 16 && psw.length() >= 8) {
            if (checkPwdFormat(psw, STRONG_PASSWORD)) {
                return 3;
            } else if (checkPwdFormat(psw, MIDDLE_PASSWORD)) {
                return 2;
            } else {
                return checkPwdFormat(psw, SICK_PASSWORD) ? 1 : 0;
            }
        } else {
            return -1;
        }
    }
}
